package com.friend.base.controller.login;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.friend.base.service.base.MemberService;
import com.friend.entity.entity.base.Member;
import com.friend.entity.model.third.WxSessionBo;
import com.friend.entity.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @program: yzh->MPWXLoginController
 * @description: 微信登录
 * @author: yangzhanghui
 * @create: 2019-09-08 11:37
 **/
@Api(value = "微信小程序登录", tags = {"微信小程序登录相关"})
@RestController
public class MPWXLoginController {

    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "微信小程序登录", notes = "根据code用户的登录与注册", httpMethod = "POST")
    @PostMapping("/mpWXLogin/{code}")
    public ResponseResult wxLogin(
            @ApiParam(name = "code", value = "通过wx.login获得的code", required = true)
            @PathVariable String code,
            @RequestBody Member member) throws Exception {
        System.out.println("wxlogin - code" + code);

        //如果whichMP为空，则默认使用默认的NEXT超英预告
        Integer whichMp = member.getWhichMP();

        String appId = "wx4fcb76b359718cfb";
        String secret = "37b80da9a8854b84412fd3db19ba1b8d";

        // https://api.weixin.qq.com/sns/jscode2session?
        // appid=APPID&
        // secret=SECRET&
        // js_code=JSCODE&
        // grant_type=authorization_code

        String url = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" +
                appId + "&secret=" + secret + "&js_code=" + code;

        String wxResult = com.learn.yzh.util.HttpClientUtil.httpGet(url, "UTF-8");
        System.out.println(wxResult);

        WxSessionBo model = JSONUtil.toBean(wxResult, WxSessionBo.class);

        //openid是微信端用户的唯一标识，需要保存到数据库
        Member userResult = memberService.getOne(new QueryWrapper<Member>().eq("mp_wx_open_id", model.getOpenid()));
        String uniqueToken = UUID.randomUUID().toString().trim();
        if (userResult == null){
            userResult = new Member();
            userResult.setMpWxOpenId(model.getOpenid());
            userResult.setNickname(member.getNickname());
            userResult.setFaceImage(member.getFaceImage());
            userResult.setBirthday(LocalDate.now().minusYears(25));
            userResult.setIsCertified(0);
            userResult.setRegistTime(LocalDateTime.now());
            userResult.setUsername(uniqueToken);
            boolean ifSave = memberService.save(userResult);
        }

        userResult.setUserUniqueToken(uniqueToken);

        return ResponseResult.ok("登录成功", userResult);
    }

    @ApiOperation(value = "第三方登录登录", notes = "第三方的登录与注册", httpMethod = "POST")
    @PostMapping("/appUnionLogin/{code}")
    public ResponseResult appUnionLogin(
            @ApiParam(name = "logintype", value = "第三方提供方类型", required = true)
            @PathVariable String logintype,
            @RequestBody Member member) throws Exception {

        System.out.println("wxlogin - code" + logintype);

        //如果whichMP为空，则默认使用默认的NEXT超英预告
        Integer whichMp = member.getWhichMP();

        String appId = "wx4fcb76b359718cfb";
        String secret = "46b918901661b6ed781b701d4cc3a00a";

        String url = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" +
                appId + "&secret=" + secret + "&js_code=";

        String wxResult = com.learn.yzh.util.HttpClientUtil.httpGet(url, "UTF-8");
        System.out.println(wxResult);

        WxSessionBo model = JSONUtil.toBean(wxResult, WxSessionBo.class);

        //openid是微信端用户的唯一标识，需要保存到数据库
        Member userResult = memberService.getOne(new QueryWrapper<Member>().eq("mp_wx_open_id", model.getOpenid()));
        String uniqueToken = UUID.randomUUID().toString().trim();
        if (userResult == null){
            userResult = new Member();
            userResult.setMpWxOpenId(model.getOpenid());
            userResult.setNickname(member.getNickname());
            userResult.setFaceImage(member.getFaceImage());
            userResult.setBirthday(LocalDate.now().minusYears(25));
            userResult.setIsCertified(0);
            userResult.setRegistTime(LocalDateTime.now());
            userResult.setUsername(uniqueToken);
            boolean ifSave = memberService.save(userResult);
        }

        userResult.setUserUniqueToken(uniqueToken);

        return ResponseResult.ok("登录成功", userResult);
    }
}
